package cn.stylefeng.guns.rabbitmq.service.impl;

import cn.stylefeng.guns.rabbitmq.config.RenStatusMsg;
import cn.stylefeng.guns.rabbitmq.model.ResultParam;
import cn.stylefeng.guns.rabbitmq.service.ICardService;
import cn.stylefeng.guns.rabbitmq.util.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("doulCardService")
@Slf4j
public class DoulCardServiceImpl implements ICardService {
    private static final String account = "18771118457";
    private static final String signKey = "ffd4511ae9f34e77b7f6d043cab58eaf";
    private static final String paramKey = "ffd4511ae9f34e77b7f6d043cab58eaf";

    @Value("${order.approveUrl}")
    private String approveUrl;

    /**
     * 发送
     *
     * @param object
     */
    @Override
    public boolean sendCardSubmit(JSONObject object) {
        log.info("豆乐销卡接收到数据：" + object.toJSONString() + "，开始提交数据到豆乐销卡");
        JSONObject order = object.getJSONObject("order");
        JSONObject orderItem = object.getJSONObject("orderItem");
        JSONObject channel = object.getJSONObject("channel");
        JSONArray channelParam = channel.getJSONArray("params");
        String httpUrl = channel.getString("apiUrl");
        Map<String, String> param = new HashMap<>();
        //先拆分固定参数
        for (Object objParam : channelParam) {
            JSONObject jsonObject = (JSONObject)objParam;
            if (!StringUtils.isEmpty(jsonObject.getString("value"))) {
                param.put(jsonObject.getString("key"), jsonObject.getString("value"));
            }
        }
        param.put("account", account);
        param.put("orderId", order.getString("orderNo"));
        param.put("uploadFace", order.getString("quota"));
        param.put("userPrice", order.getString("costRate"));
        try {
            if (!StringUtils.isEmpty(orderItem.getString("cardNo"))) {
                param.put("cardNumber", DouDes3Util.encode(paramKey, orderItem.getString("cardNo")));
            } else {
                param.put("cardNumber", "");
            }
            if (!StringUtils.isEmpty(orderItem.getString("cardPassword"))) {
                param.put("cardPwd", orderItem.getString("cardPassword"));
            } else {
                param.put("cardPwd", "");
            }

            //拼接参数顺序
            String paramMd5str = "accountorderIdcardNumbercardPwduploadFaceuserPricearea";
            for (String key : param.keySet()) {
                paramMd5str = paramMd5str.replace(key, key + param.get(key));
            }
            paramMd5str = paramMd5str.concat("" + signKey);

            String sign = EncryptionUtil.getMD5(paramMd5str).toLowerCase();
            param.put("sign", sign);
            log.info("向豆乐销卡提交数据：" + JSONObject.toJSONString(param));
            String resultStr = HttpUtil.sendPost(httpUrl, param, "utf-8");
            log.info("豆乐销卡返回：" + resultStr);
            if (!StringUtils.isEmpty(resultStr)) {
                JSONObject result = JSONObject.parseObject(resultStr);
                if (result.getString("status").equals("0")) {
                    return true;
                } else {
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", false);
                    body.put("orderNo", order.getString("orderNo"));
                    body.put("itemQuota", null);
                    body.put("payAmount", null);
                    body.put("adminApprove", false);
                    body.put("remark", "销卡渠道核销失败");
                    String resultA = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(resultA);
                    if (resJson.getBoolean("success") || resJson.getIntValue("code") == 505) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            log.error("豆乐销卡md5错误");
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 销卡回调处理
     *
     * @param param
     */
    @Override
    public boolean cardNotify(ResultParam param) {
        String orderId = param.getOrderId();
        String account = param.getAccount();
        String state = param.getState();
        String settleFace = param.getSettleFace();
        String endTime = param.getEndTime();
        String failReason = param.getFailReason();
        String failExplain = param.getFailExplain();
        String judgeFace = param.getJudgeFace();
        String sign = param.getSign();
        String[] signPre = new String[]{"account" + account, "orderId" + orderId,  "state" + state, "settleFace" + settleFace, "endTime" + endTime, "judgeFace" + judgeFace, signKey};
        String signStr = String.join("", signPre);
        log.info("豆乐销卡回调：" + signStr);
        try {
            String signMy = EncryptionUtil.getMD5(signStr).toUpperCase();
            if (signMy.equals(sign)) {
                if (state.equals("SUCCESS") ) {//成功
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", true);
                    body.put("orderNo", orderId);
                    body.put("itemQuota", settleFace);
                    //body.put("payAmount", null);
                    body.put("remark", failExplain);
                    body.put("adminApprove", false);
                    String result = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(result);
                    if (resJson.getBoolean("success")) {
                        return true;
                    }
                } else if (state.equals("FAIL")) {//失败
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", false);
                    body.put("orderNo", orderId);
                    //body.put("itemQuota", realPrice);
                    //body.put("payAmount", actualAmount);
                    body.put("remark", failExplain);
                    body.put("adminApprove", false);
                    String result = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(result);
                    if (resJson.getBoolean("success")) {
                        return true;
                    }
                }
            } else {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @return
     */
    @Override
    public Object returnOk() {
        return "Y";
    }


    public static void main(String[] args) {

        try {
            Map<String, String> param = new HashMap<>();
            param.put("account", account);
            param.put("orderId", "LX201909181756195593973102");
            param.put("cardNumber", "");
            //param.put("cardPwd", "2121212121212");
            //param.put("dateTime", DateUtil.DateToString(new Date(), DateStyle.YYYYMMDDHHMMSS));
            String retUrl = param.get("retUrl");
            param.put("uploadFace", "50");
            param.put("userPrice", "47.5");
            param.put("area", "0");
            param.put("cardPwd", "13A9FDD540F243BA");
            //拼接参数顺序
            String paramMd5str = "accountorderIdcardNumbercardPwduploadFaceuserPricearea";
            for (String key : param.keySet()) {
                paramMd5str = paramMd5str.replace(key, key + param.get(key));
            }
            paramMd5str = paramMd5str.concat(signKey);
            String sign = ShouKaUtil.MD5(paramMd5str);
            param.put("cardPwd", DouDes3Util.encode(paramKey, "13A9FDD540F243BA"));
            //param.put("cardNumber", DouDes3Util.encode(paramKey, "JDEZ190117J50158600"));

            System.out.println(paramMd5str + "-----" + sign);
            param.put("sign", sign);
            String resultStr = HttpUtil.sendPost("http://api.douleka.com:11140/api/singleSupply", param, "utf-8");
            System.out.println(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
